package tasks

import (
	"../luahelper"
	"fmt"
	lua "github.com/yuin/gopher-lua"
	"strconv"
)

func RegisterFunc_4lua(l *lua.LState) {
	l.SetGlobal("Cron", l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"AddFunc":              AddFunc_4lua,
		"AddFuncByMinutes":     AddFuncByMinutes_4lua,
		"AddFileFunc":          AddFileFunc_4lua,
		"AddFileFuncByMinutes": AddFileFuncByMinutes_4lua,
	}))
}

func AddFileFuncByMinutes_4lua(l *lua.LState) int {
	// Cron.AddFileFuncByMinutes(1, "SDK/AppConnect.lua")
	mine := l.ToNumber(1)
	if mine <= 0 {
		return luahelper.PushErrorMessage(l, "mine can not be small than 0")
	}

	file := l.ToString(2)
	if file == "" {
		return luahelper.PushErrorMessage(l, "not found lua file")
	}

	spec := fmt.Sprintf("0/%d * * * *", mine)
	id, err := AddFunc(spec, func() {
		fmt.Printf("TaskCall spec %s file %s\r\n", spec, file)
		luahelper.DofileInNewState(file)
	})
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	l.Push(lua.LBool(true))
	l.Push(lua.LNumber(id))

	return 2
}

func AddFileFunc_4lua(l *lua.LState) int {
	// Cron.AddFileFunc("* * * * *", "SDK/AppConnect.lua")

	spec := l.ToString(1)
	if spec == "" {
		return luahelper.PushErrorMessage(l, "not found spec")
	}

	luafile := l.ToString(2)
	if luafile == "" {
		return luahelper.PushErrorMessage(l, "not found lua file")
	}

	id, err := AddFunc(spec, func() {
		fmt.Printf("TaskCall spec %s file %s\r\n", spec, luafile)
		luahelper.DofileInNewState(luafile)
	})

	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	l.Push(lua.LBool(true))
	l.Push(lua.LNumber(id))
	return 2
}

func AddFunc_4lua(l *lua.LState) int {
	// Cron.AddFunc("* * * * *", function() end)

	spec := l.ToString(1)
	if spec == "" {
		return luahelper.PushErrorMessage(l, "not found spec")
	}

	fc := l.ToFunction(2)
	if fc == nil {
		return luahelper.PushErrorMessage(l, "not found function")
	}

	funcId := luahelper.RegisterLuaCallback(l, "TaskCallBack", fc)

	id, err := AddFunc(spec, func() {
		fmt.Printf("TaskCall spec %s\r\n", spec)
		luahelper.SafeCallLuaCallback(l, funcId)
	})

	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatusAndMessage(l, true, strconv.Itoa(int(id)))
}

func AddFuncByMinutes_4lua(l *lua.LState) int {
	// Cron.AddFuncBySec(5, function() end)

	sec := l.ToInt(1)
	if sec == 0 {
		return luahelper.PushErrorMessage(l, "not found sec")
	}

	fc := l.ToFunction(2)
	if fc == nil {
		return luahelper.PushErrorMessage(l, "not found function")
	}

	funcId := luahelper.RegisterLuaCallback(l, "TaskCallBack", fc)

	spec := fmt.Sprintf("0/%d * * * *", sec)
	id, err := AddFunc(spec, func() {
		fmt.Printf("TaskCall spec %s\r\n", spec)
		luahelper.SafeCallLuaCallback(l, funcId)
	})

	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatusAndMessage(l, true, strconv.Itoa(int(id)))
}
